package com.tfjybj.itoo.exam.provider.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.dmsdbj.itoo.tool.base.service.impl.BaseServicePlusImpl;
import com.tfjybj.itoo.exam.entity.CollectionRecordEntity;
import com.tfjybj.itoo.exam.entity.ExaminationEntity;
import com.tfjybj.itoo.exam.model.*;
import com.tfjybj.itoo.exam.provider.dao.CollectionRecordDao;
import com.tfjybj.itoo.exam.provider.dao.ExaminationDao;
import com.tfjybj.itoo.exam.provider.service.CollectionRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * CollectionRecordService接口实现类
 * ${base}表
 *
 * @author 王雪芬
 * @version 2.0.0
 * @since 2.0.0 2019-01-26 18:24:57
 */
@Service("collectionRecordService")
@Slf4j
public class CollectionRecordServiceImpl extends BaseServicePlusImpl<CollectionRecordDao, CollectionRecordEntity> implements CollectionRecordService {

    //region 模板生成
    @Resource
    private CollectionRecordDao collectionRecordDao;
    private ExaminationDao examinationDao;

    //endregion

    /* **********************************以下为非模板生成的内容********************************* */

    /**
     * 插入错题
     *
     * @return
     */
    @Override

    public Boolean insertWrongRecord() {
        List<PaperRecordModel> wrongRecordModels = collectionRecordDao.queryWrongRecord();
        if (wrongRecordModels == null) {
            return false;
        } else {
            for (PaperRecordModel paperRecordModel : wrongRecordModels) {
                CollectionRecordEntity collectionRecordEntity = new CollectionRecordEntity();
                BeanUtils.copyProperties(paperRecordModel, collectionRecordEntity);
                collectionRecordEntity.setId(IdWorker.getIdStr());
                collectionRecordEntity.setPaperRecordId(paperRecordModel.getId());
                collectionRecordEntity.setCreateTime(new Date());
                collectionRecordEntity.setUpdateTime(new Date());
                collectionRecordEntity.setStatus(0);
                collectionRecordEntity.setIsDelete(0);
                collectionRecordEntity.setOperator("insertWrongJob");
                collectionRecordDao.insert(collectionRecordEntity);
            }
        }

        //更新考试状态为已经插入错题表,查询考试状态为'2'和‘3’的考试,然后更新为4
        List<ExaminationEntity> examinationEntities = collectionRecordDao.queryExamByState();
        for (ExaminationEntity examinationEntity : examinationEntities) {
            examinationEntity.setState(4);
            examinationDao.updateById(examinationEntity);
        }
        return true;
    }

    /**
     * 学生交卷时把该学生的错题存入错题记录表
     *
     * @param examineeId
     * @return
     */
    @Override
    @Transactional
    public Boolean insertWrongByExamineeId(String examineeId) {
        //根据考生id查询考生错题
        List<PaperRecordModel> paperRecordModels = collectionRecordDao.queryWrongByExamineeId(examineeId);
        if (paperRecordModels == null) {
            return false;
        }
        for (PaperRecordModel paperRecordModel : paperRecordModels) {
            CollectionRecordEntity collectionRecordEntity = new CollectionRecordEntity();
            BeanUtils.copyProperties(paperRecordModel, collectionRecordEntity);
            collectionRecordEntity.setPaperRecordId(paperRecordModel.getId());
            collectionRecordEntity.setStudentAnswerArrayStr(paperRecordModel.getStudentAnswer());
            collectionRecordEntity.setStatus(0);
            collectionRecordEntity.setOperator("insertWrongJob");
            collectionRecordDao.insert(collectionRecordEntity);
        }
        return true;
    }

    /**
     * 根据考生查询错题课程和小练
     *
     * @param studentId
     * @return
     */
    @Override
    public Map<String, List<ExamCourseModel>> queryCourseExamination(Integer status, String studentId) {
        List<ExamCourseModel> examCourseModels = collectionRecordDao.queryCourseExamination(status, studentId);
        if (examCourseModels == null) {
            return null;
        } else {
            Map<String, List<ExamCourseModel>> examCourseModelMap = examCourseModels.stream().collect(Collectors.groupingBy(ExamCourseModel::getName));
            return examCourseModelMap;
        }
    }

    /**
     * 根据小练和考生查询错题的章节和题型
     *
     * @param status
     * @param examinationId
     * @param examineeId
     * @return
     * @author 李娜
     */
    @Override
    public List<ChapterQuestionTypeModel> queryChapterType(Integer status, String examinationId, String examineeId) {
        return collectionRecordDao.queryChapterType(status, examinationId, examineeId);
//        Map<String,List<ChapterQuestionTypeModel>> chapterQuestionTypeMap=chapterQuestionTypes.stream().collect(Collectors.groupingBy(ChapterQuestionTypeModel::getChapterName));
    }

    @Override
    public List<ChapterQuestionTypeModel> queryQuestionType(Integer status, String examinationId, String examineeId, String chapterId) {
        return collectionRecordDao.queryQuestionType(status, examinationId, examineeId, chapterId);
//        Map<String,List<ChapterQuestionTypeModel>> chapterQuestionTypeMap=chapterQuestionTypes.stream().collect(Collectors.groupingBy(ChapterQuestionTypeModel::getChapterName));
    }

    /**
     * 根据小练，章节题型显示学生错题信息-李娜-2019年1月29日
     *
     * @param examineeId
     * @param examinationId
     * @param questionTypeId
     * @param questionClassfiyId
     * @param status
     * @return
     * @author 李娜
     */
    @Override
    public ExamPaperModel queryWrongQuestion(String examineeId, String examinationId,
                                             String questionTypeId, String questionClassfiyId, Integer status, String templateId) {

        String score = collectionRecordDao.queryScore(templateId, questionTypeId);
        Double s;
        if (score == null) {

            s = 0.00;
        } else {
            s = Double.parseDouble(score);
        }

        List<QuestionMainModel> wrongQuestionModels = collectionRecordDao.queryWrongQuestion(examineeId, examinationId, questionTypeId, questionClassfiyId, status);
        if (wrongQuestionModels != null) {
            for (int k = 0; k < wrongQuestionModels.size(); k++) {
                QuestionMainModel questionMainModel = wrongQuestionModels.get(k);

                if (questionMainModel != null) {
                    wrongQuestionModels.get(k).setScore(s);
                    wrongQuestionModels.get(k).setQuestionMainOrder(k + 1);
                    if (wrongQuestionModels.get(k).getAnalysis() == null) {
                        wrongQuestionModels.get(k).setAnalysis("无");
                    }
                    if (wrongQuestionModels.get(k).getStudentAnswer() != null) {
                        String[] answerArray = new String[0];
                        try {
                            answerArray = questionMainModel.getStudentAnswer().split("\\|");
                        } catch (Exception e) {
                            log.error("题型id-{},题id-{},考生id-{},模板id-{},学生数组分割error-{}", questionMainModel.getQuestionTypeId(), questionMainModel.getQuestionId(), examineeId, templateId, e);
                            answerArray[0] = "";
                        }
                        wrongQuestionModels.get(k).setStudentAnswerArray(answerArray);
                    }
                }
            }
        } else {
            return null;
        }
        ExamTemPaperQuestionTypeModel examTemPaperQuestionTypeModel = new ExamTemPaperQuestionTypeModel();
        examTemPaperQuestionTypeModel.setQuestionMainModelList(wrongQuestionModels);
        examTemPaperQuestionTypeModel.setQuestionScore(score);
        if (wrongQuestionModels.size() != 0) {
            examTemPaperQuestionTypeModel.setQuestionCode(Integer.parseInt(wrongQuestionModels.get(0).getCode()));
            examTemPaperQuestionTypeModel.setQuestionName(wrongQuestionModels.get(0).getQuestionTypeName());
        }
        List<ExamTemPaperQuestionTypeModel> examTemPaperQuestionTypeModels = new ArrayList<ExamTemPaperQuestionTypeModel>();
        examTemPaperQuestionTypeModels.add(examTemPaperQuestionTypeModel);
        ExamPaperModel examPaperModel = new ExamPaperModel();
        examPaperModel.setPaperQuestionTypeList(examTemPaperQuestionTypeModels);
        return examPaperModel;
    }

    /**
     * 收藏夹-插入小题
     *
     * @return
     * @author 刘梦娇 2019年1月29日15:58:36
     */
    @Override
    public boolean insertCollection(CollectionRecordModel model) {

        //查询是否收藏该题
//        collectionRecordDao.queryQuestionCollection(model.getExamineeId(),model.getQuestionId());
        //如果为空则插入

        //如果不为空则更新操作

        List<CollectionRecordModel> collectionRecordModels = collectionRecordDao.queryQuestionCollection(model.getExamineeId(), model.getQuestionId());
        CollectionRecordEntity collectionRecordEntity = new CollectionRecordEntity();
        model.setStatus(1);
        BeanUtils.copyProperties(model, collectionRecordEntity);
        collectionRecordEntity.setId(IdWorker.getIdStr());

        if (collectionRecordModels.size() == 0) {
//          return this.save(collectionRecordEntity);
            this.save(collectionRecordEntity);
            return true;
        } else {

            return false;
        }
    }

    @Override
    public boolean cancelCollection(String examinationId, String examineeId, String questionId) {
        return collectionRecordDao.cancelCollection(examinationId, examineeId, questionId);
    }


    /**
     * 课程练习-根据课程id和题型id查询试题及选项
     *
     * @param courseId
     * @param questionTypeId
     * @return 是否查询成功
     * @author 贾建清
     * @since 2.0.0 2019-3-24 19:14:31
     */
    @Override
    public List<QuestionMainModel> queryQuestionOption(String courseId, String questionTypeId) {
        List<QuestionMainModel> questionMainModelList = collectionRecordDao.queryQuestionOption(courseId, questionTypeId);
        if( questionMainModelList != null){
            for(int i = 0; i < questionMainModelList.size(); i++){
                QuestionMainModel questionMainModel = questionMainModelList.get(i);
                if(questionMainModel != null){
                    questionMainModelList.get(i).setQuestionMainOrder(i+1);
                }
            }

        }

        return questionMainModelList;
    }
}
